//extension js that binding to background mode(extension control not be opened)
console.log("background...")
chrome.runtime.onInstalled.addListener(()=>{
    console.log("Called when extension is installed or updated!")
    //initialize setting
})
chrome.runtime.onStartup.addListener(()=>{
        console.log("Browser started, extension is active")
        chrome.tabs.onCreated.addListener((tab)=>{
            console.log(`New tab created: ${tab.id}`)
        })

        chrome.tabs.onUpdated.addListener((tabId,changeInfo,tab)=>{
            console.log(`New page loaded: : ${tab.url}`)
                chrome.tabs.onUpdated.addListener((tabId,changeInfo,tab)=>{
                    console.log(`New page loaded: : ${tab.url}`)
                    if(tab.url !== 'chrome://extensions/'){
                        // chrome.tabs.on
                        chrome.tabs.query({active:true,currentWindow:true}).then((tabs)=>{
                            if(tabs && tabs.length > 0){
                                chrome.tabs.sendMessage(tabs[0].id,{action:"myLoopAction"});
                            }
                        }).catch((err)=>{
                                console.error(err)
                        })
                    }  
            })
        })

})

chrome.runtime.onSuspend.addListener(()=>{
    console.log("Extrension is being supened")
})

chrome.runtime.onMessageExternal.addListener(()=>{
    console.log("Extrension receive message from other extension")
})

chrome.runtime.onConnect.addListener((port)=>{
    //fired when an extension or content script connects to background page
    //use this for long0lived connections
    console.log("Port connected:"+port.name)
})


//////
chrome.runtime.onMessage.addListener((message,sender,sendResponse)=>{
    if(message.action === "getData"){
        console.log("got action getData")
        sendResponse({data:"Some data from background"})
    }
})


